package com.zbkj.front.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.response.CommonResult;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.front.config.IgnoreUrlsConfig;
import com.zbkj.service.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  移动端管理端 token验证拦截器 使用前注意需要一个@Bean手动注解，否则注入无效
 * +----------------------------------------------------------------------
 * | Author:  
 * +----------------------------------------------------------------------
 */
public class AuthTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private FrontTokenComponent frontTokenComponent;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Resource
    private IgnoreUrlsConfig ignoredUrls;


    //程序处理之前需要处理的业务
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String token = frontTokenComponent.getToken(request);

        String requestURI = request.getRequestURI();
        if (ignoredUrls.getUrls().contains(requestURI)) {
            return true;
        }

        if (StringUtils.isBlank(token)) {
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        //判断用户登录key是否存在，如果登录key存在，并且登录key失效时间少于1天
        String tokenKey = Constants.USER_TOKEN_REDIS_KEY_PREFIX + token;
        boolean result = redisUtil.exists(tokenKey);
        /*if(result && redisUtil.getExpire(tokenKey) < 3600 * 24){
            Integer uid = redisUtil.get(tokenKey);
            redisUtil.set(tokenKey, uid, Constants.TOKEN_EXPRESS_MINUTES, TimeUnit.MINUTES);
        }*/
        if(!result){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        User user = userService.getLoginUserInfo();
        try {
            //检查用户有效性
            userService.userValidCheck(user);
        } catch (CommonException ec) {
            response.getWriter().write(JSONObject.toJSONString(CommonResult.failed(CommonResult.unauthorized().getCode(),ec.getMessage())));
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
